package com.paipaideli.ui.webView;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.pullrefresh.TStatusView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2019/9/12.
 */

public class WebAcyivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout topBack;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.webview)
    WebView webview;
    private String url;
    private String title;

    public static void open(Context context,String url,String title){
        Intent intent=new Intent(context,WebAcyivity.class);
        intent.putExtra("url",url);
        intent.putExtra("title",title);
        context.startActivity(intent);
    }

    @Override
    public int getContentView() {
        return R.layout.activity_webview;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);

        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        if (TextUtils.isEmpty(url)){
            url="http://www.baidu.com";
        }

        if (TextUtils.isEmpty(title)){
            topTitle.setText("网页");
        }else{
            topTitle.setText(title);
        }

        //返回
        topBack.setOnClickListener(o ->
                finish()
        );

        WebSettings webSettings = webview.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        //加载需要显示的网页
        webview.loadUrl(url);
        //设置Web视图
        webview.setWebViewClient(new webViewClient());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    //Web视图
    private class webViewClient extends WebViewClient {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    @Override
    //设置回退
    //覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack(); //goBack()表示返回WebView的上一页面
            return true;
        }
        finish();//结束退出程序
        return false;
    }

}
